package com.hhf.springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.hhf.springboot.common.DataGroupByDateDTO;
import com.hhf.springboot.common.ErrorCode;
import com.hhf.springboot.constant.CommonConstant;
import com.hhf.springboot.exception.ThrowUtils;
import com.hhf.springboot.mapper.FileInfoMapper;
import com.hhf.springboot.model.dto.fileInfo.FileInfoQueryRequest;
import com.hhf.springboot.model.entity.FileInfo;
import com.hhf.springboot.model.entity.User;
import com.hhf.springboot.model.vo.FileInfoVO;
import com.hhf.springboot.model.vo.UserVO;
import com.hhf.springboot.service.FileInfoService;
import com.hhf.springboot.service.UserService;
import com.hhf.springboot.utils.DateUtils;
import com.hhf.springboot.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 文件信息服务实现
 *
 * @author tws
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/11/20
 */
@Service
@Slf4j
public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> implements FileInfoService {


    @Resource
    private FileInfoMapper fileInfoMapper;

    @Resource
    private UserService userService;

    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Value("${server.port}")
    private String port;

    /**
     * @param file 前端传递过来的文件
     * @return
     * @throws IOException
     */
    @Override
    public String upload(MultipartFile file, HttpServletRequest request) throws IOException {
        //原始文件名称
        String originalFilename = file.getOriginalFilename();
        //原始文件后缀
        String type = FileUtil.extName(originalFilename);
        //原始文件大小
        long size = file.getSize();

        // 定义一个文件唯一的标识码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID = uuid + StrUtil.DOT + type;

        File uploadFile = new File(fileUploadPath + fileUUID);
        // 判断配置的文件目录是否存在，若不存在则创建一个新的文件目录
        File parentFile = uploadFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }


        // 获取文件的md5
        String url;
        String md5 = SecureUtil.md5(file.getInputStream());
        // 从数据库查询是否存在相同的记录
        FileInfo dbFileInfo = getFileByMd5(md5);
        if (dbFileInfo != null) { // 文件已存在
            url = dbFileInfo.getUrl();
        } else {
            // 上传文件到磁盘
            file.transferTo(uploadFile);
            // 数据库若不存在重复文件，则不删除刚才上传的文件
            url = "http://localhost:" + port + "/api/file/" + fileUUID;
        }


        //获取当前登录的用户
        User loginUser = userService.getLoginUser(request);

        // 存储数据库
        FileInfo saveFile = new FileInfo();
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setSize(size / 1024);
        saveFile.setUrl(url);
        saveFile.setUserId(loginUser.getId());
        saveFile.setMd5(md5);
        fileInfoMapper.insert(saveFile);

        return url;
    }

    /**
     * 文件下载接口   http://localhost:8081/file/{fileUUID}
     *
     * @param fileUUID
     * @param response
     * @throws IOException
     */
    @Override
    public void download(String fileUUID, HttpServletResponse response) throws IOException {

        log.info("当前的文件保存路径为:" + fileUploadPath);

        // 根据文件的唯一标识码获取文件
        File uploadFile = new File(fileUploadPath + fileUUID);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        // 读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }


    /**
     * 校验数据
     *
     * @param fileInfo
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validFileInfo(FileInfo fileInfo, boolean add) {
        ThrowUtils.throwIf(fileInfo == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        String name = fileInfo.getName();

        // 创建数据时，参数不能为空
        if (add) {
            // 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(name), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        // 补充校验规则
        if (StringUtils.isNotBlank(name)) {
            ThrowUtils.throwIf(name.length() > 80, ErrorCode.PARAMS_ERROR, "文件名过长");
        }
    }

    /**
     * 获取查询条件
     *
     * @param fileInfoQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<FileInfo> getQueryWrapper(FileInfoQueryRequest fileInfoQueryRequest) {
        QueryWrapper<FileInfo> queryWrapper = new QueryWrapper<>();
        if (fileInfoQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = fileInfoQueryRequest.getId();
        String name = fileInfoQueryRequest.getName();
        String type = fileInfoQueryRequest.getType();
        String sortField = fileInfoQueryRequest.getSortField();
        String sortOrder = fileInfoQueryRequest.getSortOrder();
        Long userId = fileInfoQueryRequest.getUserId();
        // 补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(name)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", name));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.like(StringUtils.isNotBlank(type), "type", type);

        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "user_id", userId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取文件信息封装
     *
     * @param fileInfo
     * @param request
     * @return
     */
    @Override
    public FileInfoVO getFileInfoVO(FileInfo fileInfo, HttpServletRequest request) {
        // 对象转封装类
        FileInfoVO fileInfoVO = new FileInfoVO();
        BeanUtil.copyProperties(fileInfo, fileInfoVO);

        // 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = fileInfo.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        fileInfoVO.setUser(userVO);

        return fileInfoVO;
    }

    /**
     * 分页获取文件信息封装
     *
     * @param fileInfoPage
     * @param request
     * @return
     */
    @Override
    public Page<FileInfoVO> getFileInfoVOPage(Page<FileInfo> fileInfoPage, HttpServletRequest request) {
        List<FileInfo> fileInfoList = fileInfoPage.getRecords();
        Page<FileInfoVO> fileInfoVOPage = new Page<>(fileInfoPage.getCurrent(), fileInfoPage.getSize(), fileInfoPage.getTotal());
        if (CollUtil.isEmpty(fileInfoList)) {
            return fileInfoVOPage;
        }
        // 对象列表 => 封装对象列表
        List<FileInfoVO> fileInfoVOList = fileInfoList.stream().map(fileInfo -> {
            FileInfoVO fileInfoVO = new FileInfoVO();
            BeanUtil.copyProperties(fileInfo, fileInfoVO);
            return fileInfoVO;
        }).collect(Collectors.toList());

        // 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = fileInfoList.stream().map(FileInfo::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));

        // 填充信息
        fileInfoVOList.forEach(fileInfoVO -> {
            Long userId = fileInfoVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            fileInfoVO.setUser(userService.getUserVO(user));
        });

        fileInfoVOPage.setRecords(fileInfoVOList);
        return fileInfoVOPage;
    }


    /**
     * 通过文件的md5查询文件
     *
     * @param md5
     * @return
     */
    private FileInfo getFileByMd5(String md5) {
        // 查询文件的md5是否存在
        QueryWrapper<FileInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5", md5);
        List<FileInfo> filesList = fileInfoMapper.selectList(queryWrapper);
        return filesList.size() == 0 ? null : filesList.get(0);
    }

    /**
     * 分按日期分组查询任务管理信息新增数量
     *
     * @param beginDate 开始时间
     * @param endDate   结束时间
     * @return
     */
    @Override
    public List<DataGroupByDateDTO> countByDay(Date beginDate, Date endDate) {
        QueryWrapper<FileInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DATE_FORMAT(create_time, '%Y-%m-%d') AS day", "COUNT(1) AS num");
        queryWrapper.ge("create_time", beginDate);
        queryWrapper.le("create_time", endDate);
        queryWrapper.groupBy("day");
        queryWrapper.orderByAsc("day");
        // 执行查询
        List<Map<String, Object>> results = this.baseMapper.selectMaps(queryWrapper);
        // 映射到 DataGroupByDateDTO
        return results.stream().map(result -> {
            DataGroupByDateDTO dto = new DataGroupByDateDTO();
            dto.setDay(DateUtils.parse(result.get("day").toString(), DateUtils.FMT_YMD));
            dto.setNum((Long) result.get("num"));
            return dto;
        }).collect(Collectors.toList());
    }

}
